package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;

public class IoTest {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		ioStream();
//		StringCode();
		//copyFile(new File("c:/login.properties"), "d:/login.properties");
	}

	/**
	 * io中存在的编码问题
	 * 
	 * @throws IOException
	 */
	private static void ioStream() throws IOException {
		//String file = "C:/stream.txt";
		String file="D:/KuGou/Lyric/毕业歌 蓝色蝴蝶-b4bd57d59f4d91a484e5db89ace0fb72.krc";
		String charset = "gbk";

//		// 写字符转换成字节流
//		FileOutputStream outputStream = new FileOutputStream(file);
//		OutputStreamWriter writer = new OutputStreamWriter(outputStream,
//				charset);
//		try {
//			writer.write("中");
//		} finally {
//			writer.close();
//		}

		// 读取字节到字符
		FileInputStream inputStream = new FileInputStream(file);
		InputStreamReader reader = new InputStreamReader(inputStream, charset);
		StringBuffer buffer = new StringBuffer();
		char[] buf = new char[64];
		int count = 0;
		try {
			while ((count = reader.read(buf)) != -1) {
				buffer.append(buf, 0, count);
			}
		} finally {
			reader.close();
		}
		System.out.println(buffer.toString());
	}

	/**
	 * 字符串中出现的编码问题
	 * 
	 * @throws UnsupportedEncodingException
	 */
	private static void StringCode() throws UnsupportedEncodingException {
		String s = "这是一段中文字符串";
		byte[] b = s.getBytes("UTF-8");
		System.out.println(new String(b, "UTF-8"));
		// System.out.println(new String(b,"ISO-8859-1"));

		Charset charset = Charset.forName("UTF-8");
		ByteBuffer byteBuffer = charset.encode("中"); // 字节缓冲区
		System.out.println(ByteToHex.bytesToBinaryString(byteBuffer.array()));
		System.out.println(ByteToHex.bytesToHexString(byteBuffer.array()));
		System.out.println(new String(ByteToHex.hexStringToBytes(ByteToHex
				.bytesToHexString(byteBuffer.array())), "UTF-8"));
		CharBuffer charBuffer = charset.decode(byteBuffer);
		System.out.println(charBuffer.toString());
	}

	private static void copyFile(File file, String newPath)
			throws FileNotFoundException, IOException {
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(file);
			os = new FileOutputStream(new File(newPath));
			IOUtils.copy(is, os);
		} finally {
			IOUtils.closeQuietly(is);
			IOUtils.closeQuietly(os);
		}
	}
}
